package com.TheyChat.service.config.auth;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

@Component
public class RsaUtil {
    private String publicKey;
    private String privateKey;
    private RSA rsa;
    public RsaUtil() throws FileNotFoundException {
        File publicFile = ResourceUtils.getFile("classpath:key/public_key.pem");
        this.publicKey= FileReader.create(publicFile).readString();
        File privateFile = ResourceUtils.getFile("classpath:key/private_key.pem");
        this.privateKey= FileReader.create(privateFile).readString();
//获取公钥，可以给任何人
        this.rsa=new RSA(this.privateKey,this.publicKey);

    }

    public String encoder(String sourceStr) {
        return this.rsa.encryptBase64(sourceStr, KeyType.PublicKey);
    }
    public String decoder(String encryptedStr){
        return this.rsa.decryptStr(encryptedStr, KeyType.PrivateKey);
    }
//    public static void main(String[] args) throws FileNotFoundException {
//        RsaUtil rsaUtil=new RsaUtil();
//       String encryptStr="TaMdDsuCPNdzO2Cl4Jj3CYQMEFmKVMEuQZRajF2rRqSyFhY6PAvi0TITbZC+vlJI4CgvEykp3kE4jiajcULRvg==";
////               rsaUtil.encoder("123456");
//       System.out.println(encryptStr);
//       System.out.println("\n解密*****************\n");
//       System.out.println(rsaUtil.decoder(encryptStr));
//    }
}
